import request from '@/utils/request'

export function jsonsqlForSelect(parameter) {
  return request({
    url: '/json/select',
    method: 'post',
    data: parameter
  })
}

export function jsonsqlForInsert(parameter) {
  return request({
    url: '/json/insert',
    method: 'post',
    data: parameter
  })
}

export function jsonsqlForUpdate(parameter) {
  return request({
    url: '/json/update',
    method: 'post',
    data: parameter
  })
}

export function jsonsqlForDelete(parameter) {
  return request({
    url: '/json/delete',
    method: 'post',
    data: parameter
  })
}


function parseXmlData(elements, result = []) {
  elements.forEach(item =>{
    if (item.hasOwnProperty('attributes') && item.attributes.hasOwnProperty('camunda:formKey')) {
      result.push(item.attributes['camunda:formKey'])
    }
    if (item.hasOwnProperty('elements')) {
      return parseXmlData(item.elements,result)
    }
  })
  return result
}

function parseData(elements, result = {}) {
  elements.forEach(obj =>{
    JSON.parse(obj).list.forEach(item =>{
      if(item.type == 'grid'){
        item.columns.forEach(temp =>{
          if(temp.list.length > 0){
            result[temp.list[0].model] = temp.list[0].name
          }
        })
      } else {
        result[item.model] = item.name
      }
    })
  })
  return result
}

export function parsepRrocessXmlData(json){
  const arr = parseXmlData(json.elements)
  return parseData(arr)
}


export function clearChildren(arr, childName) {
  if (arr[childName].length === 0) {
    delete arr[childName];
  } else {
    arr[childName].map(item => {
      clearChildren(item, childName);
    })
  }
}

export function getTreeData(source, rootKeyy) {
  let cloneData = JSON.parse(JSON.stringify(source)); // 对源数据深度克隆
  return cloneData.filter(father => {
    // 循环所有项，并添加children属性
    let branchArr = cloneData.filter(child => father.id == child.parentId); // 返回每一项的子级数组
    branchArr.length > 0 ? (father.children = branchArr) : ""; //给父级添加一个children属性，并赋值
    return father.parentId == rootKeyy; //返回第一层
  });
}

export function formatJson(filterVal, jsonData) {
  return jsonData.map(v =>
    filterVal.map(j => {
      if (j === "timestamp") {
        return parseTime(v[j]);
      } else {
        return v[j];
      }
    })
  );
}
